package com.ck.chuangke.service.impl;

import com.ck.chuangke.service.CkCompanyService;
import com.ck.common.service.ModuleService;
import com.ck.common.service.OperationLogService;
import com.ck.common.service.RoleService;
import com.ck.common.service.UserService;
import com.ck.constant.BusinessConstant;
import com.ck.constant.DateFormatConstant;
import com.ck.constant.ModuleConstant;
import com.ck.constant.RequestConstant;
import com.ck.dao.CompanyMapper;
import com.ck.exception.ServiceException;
import com.ck.model.chuangke.vo.CkCompanySelectListVO;
import com.ck.model.chuangke.vo.CkDeviceCodeListExportVO;
import com.ck.model.common.*;
import com.ck.model.common.page.PageInfo;
import com.ck.model.chuangke.vo.CkCompanyListVO;
import com.ck.util.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.rmi.ServerException;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @ClassName CkCompanyServiceImpl
 * @Description 创客后台-商家Service实现类
 * @Author HanQinrui
 * @Date 2018/6/21 11:24
 * @Version 1.0
 **/
@Transactional(rollbackFor = Exception.class)
@Service(value = "ckCompanyService")
public class CkCompanyServiceImpl implements CkCompanyService {
    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private OperationLogService operationLogService;
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private ModuleService moduleService;

    /**
     * 获取商家总数
     * @return
     */
    @Override
    public Long getCompanyCount() {
        return companyMapper.getCompanyCount();
    }

    /**
     * 商家列表分页查询
     * @param companyName
     * @param mobilePhone
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<CkCompanyListVO> listByPage(String companyName, String mobilePhone, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Page<Company> page = companyMapper.listPageCk(companyName, mobilePhone);
        if(page == null) {
            return new PageInfo<>(pageNum, pageSize, 0, Lists.newArrayList());
        }

        // 把page转为pageInfo
        PageInfo<CkCompanyListVO> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(pageNum);
        pageInfo.setPageSize(pageSize);
        pageInfo.setTotal(page.getTotal());
        List<Company> resultList = page.getResult();

        // 把返回结果集封装成List<CkCompanyListVO>
        List<CkCompanyListVO> ckCompanyListVOList = Lists.newArrayList();
        for(Company company : resultList) {
            CkCompanyListVO vo = new CkCompanyListVO();
            vo.setBusinessLicenseNo(company.getBusinessLicenseNo());
            vo.setCompanyCode(company.getCompanyCode());
            vo.setCompanyId(company.getCompanyId());
            vo.setCompanyName(company.getCompanyName());
            vo.setContacts(company.getContacts());
            vo.setMobilePhone(company.getMobilePhone());
            Long addTime = company.getAddTime();
            if(addTime == null) {
                vo.setAddTime("");
            }else {
                String stringDate = DateUtils.longTimeStampToStringDate(addTime, DateFormatConstant.LONG_DATE_FORMAT_STR);
                vo.setAddTime(stringDate);
            }
            ckCompanyListVOList.add(vo);
        }
        pageInfo.setList(ckCompanyListVOList);

        return pageInfo;
    }

    /**
     * 导出商家列表
     *
     * @param companyName
     * @param mobilePhone
     * @return
     */
    @Override
    public List<CkCompanyListVO> listExportCompany(String companyName, String mobilePhone) {
        Page<Company> page = companyMapper.listPageCk(companyName, mobilePhone);
        if(page == null) {
            return Lists.newArrayList();
        }
        List<Company> resultList = page.getResult();
        // 把返回结果集封装成List<CkCompanyListVO>
        List<CkCompanyListVO> ckCompanyListVOList = Lists.newArrayList();
        for(Company company : resultList) {
            CkCompanyListVO vo = new CkCompanyListVO();
            vo.setBusinessLicenseNo(company.getBusinessLicenseNo());
            vo.setCompanyCode(company.getCompanyCode());
            vo.setCompanyId(company.getCompanyId());
            vo.setCompanyName(company.getCompanyName());
            vo.setContacts(company.getContacts());
            vo.setMobilePhone(company.getMobilePhone());
            Long addTime = company.getAddTime();
            if(addTime == null) {
                vo.setAddTime("");
            }else {
                String stringDate = DateUtils.longTimeStampToStringDate(addTime, DateFormatConstant.LONG_DATE_FORMAT_STR);
                vo.setAddTime(stringDate);
            }
            ckCompanyListVOList.add(vo);
        }
        return ckCompanyListVOList;
    }

    /**
     * 通过商家id查询商家详细信息
     * @param companyId 商家id
     * @return
     */
    @Override
    public Company getCompanyInfoById(String companyId) {
        return companyMapper.getCompanyInfoById(companyId);
    }

    /**
     * 修改商家详细信息
     * @param company 商家信息
     */
    @Override
    public void updateCompany(Company company, HttpServletRequest request) {
        User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
        Long companyId = company.getCompanyId();
        Company oldCompany = companyMapper.getCompanyInfoById(companyId.toString());
        // 修改时间
        oldCompany.setUpdateTime(System.currentTimeMillis());
        oldCompany.setCompanyName(company.getCompanyName());
        oldCompany.setCompanyLogoUrl(company.getCompanyLogoUrl());
        oldCompany.setBusinessLicenseNo(company.getBusinessLicenseNo());
        oldCompany.setBusinessLicenseUrl(company.getBusinessLicenseUrl());
        oldCompany.setLegalPersonIdFrontUrl(company.getLegalPersonIdFrontUrl());
        oldCompany.setLegalPersonIdBackUrl(company.getLegalPersonIdBackUrl());
        oldCompany.setContacts(company.getContacts());
        oldCompany.setMobilePhone(company.getMobilePhone());

        companyMapper.updateByPrimaryKey(oldCompany);

        // 修改ck_user相关信息
        User user = userService.getUserByUserName(company.getLoginUserName());
        if(user != null) {
            user.setMobilePhone(company.getMobilePhone());
            user.setRealname(company.getCompanyName());
            userService.updateByPrimaryKey(user);
        }

        // 保存操作日志
        OperationLog operationLog = new OperationLog();
        operationLog.setCopmanyCode(loginUser.getCompanyCode());
        operationLog.setOperationContent("修改商家：" + company.getCompanyName() + "的信息");
        operationLog.setOperationStatus(BusinessConstant.OPERATION_LONG_OPERATION_STATUS_SUCCESS);
        operationLog.setOperationTime(System.currentTimeMillis());
        operationLog.setOperationModule(ModuleConstant.MODULE_COMPANY);
        operationLog.setRealname(loginUser.getRealname());
        operationLog.setUserName(loginUser.getUserName());
        operationLog.setOperationIp(HttpUtils.getRemortIP(request));
        operationLogService.saveOperationLog(operationLog);
    }

    /**
     * 新增商家
     *  @param company 商家信息
     * @param excelDeviceCode 机器码(之间用逗号隔开)
     * @param request
     */
    @Override
    public void addCompany(Company company, String excelDeviceCode, HttpServletRequest request) throws ServerException, ServiceException {
        User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
        Long curTime = System.currentTimeMillis();
        // 创建时间
        company.setAddTime(curTime);
        // 生成商家编码:时间 + 4位随机数
        Random random = new Random();
        String randomStr = String.valueOf(random.nextInt(9000) + 1000);
        String companyCode = curTime + randomStr;
        company.setCompanyCode(companyCode);
        company.setAddUserName(loginUser.getUserName());
        String password = company.getLoginPassword();
        String md5Password = DigestUtils.md5Hex(password);
        company.setLoginPassword(md5Password);
        companyMapper.insertSelective(company);

        // 添加超级管理员角色到ck_role，并把ck_module中type=1的moduleId给ck_role_module
        // 查询得到商家类型的所有ModuleId
        List<String> moduleIdList = moduleService.listModuleIdByModuleType(BusinessConstant.TYPYE_CP);
        String moduleIds = Joiner.on(",").join(moduleIdList);

        // 为该商家添加默认的角色：超级管理员
        Role role = new Role();
        role.setCompanyCode(companyCode);
        role.setRoleName("超级管理员");
        // 状态（0：启用；1：禁用）
        role.setStatus(BusinessConstant.STATUS_ENABLE);
        role.setAddTime(System.currentTimeMillis());
        // 是否超级管理员 0：是; 1：不是
        role.setSuperAdminRole(0);
        roleService.insertRole(role, moduleIds, request);
        Long roleId = role.getRoleId();
        if(roleId == null) {
            throw new ServerException("新增商家失败");
        }

        // 为该商家添加默认的用户到ck_user，并绑定用户和角色关系
        User user = new User();
        // 商家编码
        user.setCompanyCode(companyCode);
        // 用户名即登陆账号
        user.setUserName(company.getLoginUserName());
        // 真实姓名即商家名称
        user.setRealname(company.getCompanyName());
        // 密码
        user.setPassword(password);
        // 手机号码
        user.setMobilePhone(company.getMobilePhone());
        // 用户类型（0：创客用户；1：商家用户）
        user.setType(BusinessConstant.TYPYE_CP);
        // 状态（0：启用；1：禁用）
        user.setStatus(BusinessConstant.STATUS_ENABLE);
        // 是否是超级管理员用户(0：是; 1：不是)
        user.setSuperAdminUser(0);
        userService.insertUser(user, roleId.toString(), request);

        if(StringUtils.isNotBlank(excelDeviceCode)) {
            // 添加商家和机器码信息到ck_company_device
            CompanyDevice companyDevice = new CompanyDevice();
            companyDevice.setCompanyCode(companyCode);
            companyDevice.setDeviceCodeArray(excelDeviceCode.split(","));
            companyDevice.setAddTime(System.currentTimeMillis());
            companyDevice.setAddUserName(loginUser.getUserName());
            companyMapper.insertCompanyDevice(companyDevice);
        }
        // 保存操作日志
        OperationLog operationLog = new OperationLog();
        operationLog.setCopmanyCode(loginUser.getCompanyCode());
        operationLog.setOperationContent("新增商家：" + company.getCompanyName());
        operationLog.setOperationStatus(BusinessConstant.OPERATION_LONG_OPERATION_STATUS_SUCCESS);
        operationLog.setOperationTime(System.currentTimeMillis());
        operationLog.setOperationModule(ModuleConstant.MODULE_COMPANY);
        operationLog.setRealname(loginUser.getRealname());
        operationLog.setUserName(loginUser.getUserName());
        operationLog.setOperationIp(HttpUtils.getRemortIP(request));
        operationLogService.saveOperationLog(operationLog);
    }

    /**
     * 通过商家名称获取商家条数
     * @param companyName 商家名称
     * @return
     */
    @Override
    public Company getCompanyCountByCompanyName(String companyName) {
        return companyMapper.getCompanyCountByCompanyName(companyName);
    }

    /**
     * 商家下拉列表
     * @return List<CkCompanySelectListVO>
     */
    @Override
    public List<CkCompanySelectListVO> listSelect() {
        return companyMapper.listSelect();
    }

    /**
     * 通过商家代码查找对应的超级管理员信息
     * @param companyCode 商家代码
     * @return
     */
    @Override
    public User getAdminUserByCompanyCode(String companyCode) {
        return companyMapper.getAdminUserByCompanyCode(companyCode);
    }

    /**
     * @Description 商家管理上传图片
     * @Param [files, request]
     * @return Map<String,Object>
     * @Date 2018/7/24 18:05
     * @Author hanqr
     */
    @Override
    public Map<String, Object> savePicture(MultipartFile pictureFile, HttpServletRequest request) throws IOException {
        User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
        String companyCode = loginUser.getCompanyCode();
        //将图片上传至华为云
        String url = HuaWeiCloudUtils.uploadFile2HuaweiCloud(pictureFile, companyCode + "/picture/");
        //获取图片md5值
        File file = FileUtils.multipartFileConvertFile(pictureFile);
        //把MultipartFile转化为File,会在本地创建文件，用完file后，需要删除
        if (file.exists()) {
            file.delete();
        }
        Map<String, Object> pictureMap = Maps.newHashMap();
        pictureMap.put("url", url);
        pictureMap.put("file", url);
        return pictureMap;
    }

    /**
     * 通过商家代码查询商家信息
     * @param companyCode 商家代码
     * @return com.ck.model.common.Company 商家信息
     * @Date 2018/7/25 15:34
     * @Author hanqr
     */
    @Override
    public Company getCompanyInfoByCompanyCode(String companyCode) {
        return companyMapper.getCompanyInfoByCompanyCode(companyCode);
    }

    /**
     * 修改商家关联的机器码
     * @param companyCode 商家代码
     * @param deviceCode  机器码(用逗号隔开)
     * @param request
     */
    @Override
    public void updateDeviceCode(String companyCode, String deviceCode, HttpServletRequest request) throws ServiceException {
        User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
        // 通过companyCode查询商家信息
        Company company = companyMapper.getCompanyInfoByCompanyCode(companyCode);
        if(company == null) {
            throw new ServiceException("商家不存在");
        }
        // 先删除商家关联的所有机器码
        companyMapper.deleteDeviceCodeByCompanyCode(companyCode);
        // 再添加商家和机器码信息到ck_company_device
        CompanyDevice companyDevice = new CompanyDevice();
        companyDevice.setCompanyCode(companyCode);
        companyDevice.setDeviceCodeArray(deviceCode.split(","));
        companyDevice.setAddTime(System.currentTimeMillis());
        companyDevice.setAddUserName(loginUser.getUserName());
        companyMapper.insertCompanyDevice(companyDevice);
        // 保存操作日志
        OperationLog operationLog = new OperationLog();
        operationLog.setCopmanyCode(loginUser.getCompanyCode());
        operationLog.setOperationContent("修改商家：" + company.getCompanyName() +"关联的机器码文件");
        operationLog.setOperationStatus(BusinessConstant.OPERATION_LONG_OPERATION_STATUS_SUCCESS);
        operationLog.setOperationTime(System.currentTimeMillis());
        operationLog.setOperationModule(ModuleConstant.MODULE_COMPANY);
        operationLog.setRealname(loginUser.getRealname());
        operationLog.setUserName(loginUser.getUserName());
        operationLog.setOperationIp(HttpUtils.getRemortIP(request));
        operationLogService.saveOperationLog(operationLog);
    }

    /**
     * 查询所有已绑定商家的终端机器码列表
     * hanqr 2018-08-15
     * @return
     */
    @Override
    public List<String> getCompanyDeviceCodeList() {
        return companyMapper.getCompanyDeviceCodeList();
    }

    /**
     * 根据商家代码查询机器码List
     * @param companyCode 商家代码
     * @return
     */
    @Override
    public List<CkDeviceCodeListExportVO> getDeviceCodeListByCompanyCode(String companyCode) {
        return companyMapper.getDeviceCodeListByCompanyCode(companyCode);
    }
}
